import store from '../store'
import router from '../router'
import { Toast, Locale } from 'vant'
import { i18n, locale } from '@/locales'

export const isAndroid = navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Linux') > -1

export const isIPhone = navigator.userAgent.indexOf('iPhone') > -1

export const isIPad = navigator.userAgent.indexOf('iPad') > -1

export const isIPod = navigator.userAgent.indexOf('iOS') > -1

export const isWeChat = navigator.userAgent.indexOf('MicroMessenger') > -1

export const isQQ = navigator.userAgent.indexOf(' QQ') > -1

export const nowVersion = "1.0.0"

export const rootUrl = import.meta.env.VITE_BASIC_URL

//退出
export const logOut = () => {
    router.replace('/login')
    localStorage.removeItem('user')
    store.commit('change_user',{})
    store.commit('change_token','')
}
// 设置语言
export const setLocale = (e) => {
    let item = locale.find((item) => {
        return item.value == e
    })
    // i18n.global.locale = item.value
    Locale.use(e, item.vantvalue)
    store.commit('setLanguage',e)
}
//转换json格式
export const isJSON = s => {
    try {
        JSON.parse(s)
    } catch (e) {
        return false
    }
    return true
}

// 延迟的防抖动函数 当持续触发事件时，一定时间段内没有再触发事件，事件处理函数才会执行一次，如果设定的时间到来之前，又一次触发了事件，就重新开始延时，知道用户不在触发后的一定时间内才执行该处理函数。
export const debounce = (callback, delay = 1000) => {
    let timer
    return function () {
        if (timer) clearTimeout(timer)
        timer = setTimeout(() => {
            callback()
        }, delay)
    }
}

//节流是将多次执行变成每隔一段时间执行，即n秒内只执行一次
export const throttle = (func, delay = 1000 ) =>{
    let canRun=true
    return function(){
        if(!canRun) return
        canRun=false
        setTimeout(() => {
            func.apply(this,arguments)
            canRun=true
        }, delay)
    }
}

//'x'.padStart(5, 'ab') // 'ababx' 字符串补全长度
export const formatNumber = number => String(number).padStart(2, '0')

//四舍五入小数点后几位数
export const formatMoney = money => Number(money).toFixed(2)

//时间戳转换事件
export const timeFormat = time => {
    var date = new Date(time)
    let year = date.getFullYear()
    let month = date.getMonth() + 1
    let day = date.getDate()
    let hour = date.getHours()
    let minute = date.getMinutes()
    let second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

export const formatDate = date => {
    let year = date.getFullYear()
    let month = date.getMonth() + 1
    let day = date.getDate()

    return [year, month, day].map(formatNumber).join('-')
}

export const formatTime = date => {
    let year = date.getFullYear()
    let month = date.getMonth() + 1
    let day = date.getDate()
    let hour = date.getHours()
    let minute = date.getMinutes()
    let second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

//复制
export const copyTextToClipboard = text => {
    var textArea = document.createElement("textarea")
    textArea.style.position = 'fixed'
    textArea.style.top = 0
    textArea.style.left = 0
    textArea.style.width = '2em'
    textArea.style.height = '2em'
    textArea.style.padding = 0
    textArea.style.border = 'none'
    textArea.style.outline = 'none'
    textArea.style.boxShadow = 'none'
    textArea.style.background = 'transparent'
    textArea.value = text
	
    document.body.appendChild(textArea)

    textArea.select()
	document.execCommand('copy')
    try {
        if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)) {//区分iPhone设备
        textArea.setSelectionRange(0, textArea.value.length);   //兼容ios
        }
        document.execCommand('copy')
        // alert('copy success')
        Toast(i18n.global.t('config.copy'))
    } catch (err) {
        console.log('failure')
    }
    document.body.removeChild(textArea)
}

//居中
export const resizeGameStage = $el => {
    let widthRatio = window.innerWidth / 375
    let heightRatio = window.innerHeight / 667
    let positionTop = (window.innerHeight - 667) * 0.5
    let positionLeft = (window.innerWidth - 375) * 0.5

    $el.style = `
        position: fixed;
        top: ${positionTop}px;
        left: ${positionLeft}px;
        transform: scale(${Math.min(widthRatio, heightRatio)});
    `
}

// 图片压缩
export const imageCompress = (file, quality = 0.7, success, error) => {
    // 小于512K不压缩
    if (file.size < 524288) {
        success(file)
        return
    }

    const name = file.name // 文件名
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = (e) => {
        const src = e.target.result

        const img = new Image()
        img.src = src
        img.onload = () => {
            const w = img.width
            const h = img.height
            // 生成canvas
            const canvas = document.createElement('canvas')
            const ctx = canvas.getContext('2d')
            // 创建属性节点
            const anw = document.createAttribute('width')
            anw.nodeValue = w
            const anh = document.createAttribute('height')
            anh.nodeValue = h
            canvas.setAttributeNode(anw)
            canvas.setAttributeNode(anh)

            // 铺底色 PNG转JPEG时透明区域会变黑色
            ctx.fillStyle = '#fff'
            ctx.fillRect(0, 0, w, h)

            ctx.drawImage(img, 0, 0, w, h)
            // quality值越小，所绘制出的图像越模糊
            const base64 = canvas.toDataURL('image/jpeg', quality) // 图片格式jpeg或webp可以选0-1质量区间

            // 返回base64转blob的值
            // console.log(`原图${(src.length/1024).toFixed(2)}kb`, `新图${(base64.length/1024).toFixed(2)}kb`)
            // 去掉url的头，并转换为byte
            const bytes = window.atob(base64.split(',')[1])
            // 处理异常,将ascii码小于0的转换为大于0
            const ab = new ArrayBuffer(bytes.length)
            const ia = new Uint8Array(ab)
            for (let i = 0; i < bytes.length; i++) {
                ia[i] = bytes.charCodeAt(i)
            }
            file = new Blob([ab], {type: 'image/jpeg'})
            file.name = name

            success(file)
        }
        img.onerror = () => {
            error('error')
        }
    }
    reader.onerror = () => {
        error('error')
    }
}

//HTML和JavaScript读写本地文件
export const blobToFile = (theBlob) => {
    let file = new File([theBlob], theBlob.name, {type: theBlob.type})
    return file
}

//下载图片
export const downloadIamge = (selector, name) => {
    var image = new Image()
    // 解决跨域 Canvas 污染问题
    image.setAttribute('crossOrigin', 'anonymous')
    image.onload = function () {
        var canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height

        var context = canvas.getContext('2d')
        context.drawImage(image, 0, 0, image.width, image.height)
        var url = canvas.toDataURL('image/png')

        // 生成一个a元素
        var a = document.createElement('a')
        // 创建一个单击事件
        var event = new MouseEvent('click')

        // 将a的download属性设置为我们想要下载的图片名称，若name不存在则使用‘下载图片名称’作为默认名称
        a.download = name || 'save'
        // 将生成的URL设置为a.href属性
        a.href = url

        // 触发a的单击事件
        a.dispatchEvent(event)
    }

    image.src = selector

    return true
}
// 将图片转换为Base64
export const imageUrlToBase64 = (e,callback) => {
    let files = e.target.files[0]
    let fileSize = 0
    if(files){
        fileSize =files.size;          
        if (fileSize > 10*1024*1024) {
            return false
        }else if (fileSize <= 0) {
            return false
        }
    }else{
        return false
    }

    //转码base64
    let reader = new FileReader()
    let imgFile
    reader.readAsDataURL(files)
    reader.onload = e => {
        imgFile = e.target.result
        callback(imgFile)
    }
}